package com.xiaobai.monitor;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ThreadSafetyOfLocalVariables {
    private static int loopNumber = 200;
    private static int ThreadNumber = 2;
    public static void main(String[] args) {
        ThreadUnsafe threadUnsafe = new ThreadUnsafe();
        for (int i = 0; i < ThreadNumber; i++) {
            new Thread(()->{threadUnsafe.method(loopNumber);},String.valueOf(i)).start();
        }
    }
}
class ThreadUnsafe {
    //如果局部变量没有暴露给外部的话 那么他就是线程安全的
    //加上final防止子类去修改这个逻辑
   public final void method(int loopNumber){
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < loopNumber; i++) {
            add(arrayList);
            remove(arrayList);
        }
    }
    private void add(List<String> arrayList){
        arrayList.add("1");
    }
    //如果是private的话 子类是不能对这个修改的 那么还是线程安全的
    private void remove(List<String> arrayList){
        arrayList.remove(0);
    }
}
class ThreadSafeSubClass extends ThreadUnsafe {
    //这个就是新的方法而已
//    @Override
    public void remove(List<String> arrayList){
       new Thread(()->{
           arrayList.remove(0);
       }).start();
    }
}
